//
// Created by HP on 2025/11/17.
//
#include "../include/Headler.h"
#include "../model/Ticket.h"
#include "../model/Order.h"
#include "../model/User.h"
#include "../include/jwt.h"
#include <sstream>
#include <algorithm>

/**
 * 获取仪表板统计数据函数
 * 该函数用于获取今日的各种统计数据，包括收入、订单数、活跃用户等
 * @param req HTTP请求对象
 * @param res HTTP响应对象
 */
void getDashBoardStatistics(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    // 获取今日和明天的日期字符串
    std::string today = getToday();
    std::string tomorrow = addDay(today, 1);

    // todayRevenue
    std::string sql = "SELECT SUM(o.totalPrice) AS todayRevenue FROM sales s JOIN orders o ON s.orderId = o.id WHERE s.saleTime BETWEEN '" + today + "' AND '" + tomorrow + "';";

    auto result = DBConnector::getInstance()->query(sql);
    std::string todayRevenue = "0.00";
    if (!result.empty()) {
        todayRevenue = result[0]["todayRevenue"];
    }

    // todayOrders
    sql = "SELECT COUNT(*) AS todayOrders FROM orders WHERE createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string todayOrders = "0";

    if (!result.empty()) {
        todayOrders = result[0]["todayOrders"];
    }

    // activeUsers
    sql = "SELECT COUNT(DISTINCT userId) AS browseUserCount FROM browses WHERE browseTime BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string activeUsers = "0";

    if (!result.empty()) {
        activeUsers = result[0]["browseUserCount"];
    }

    // pendingOrders
    sql = "SELECT COUNT(*) AS pendingOrders FROM orders WHERE status = 'ordered' AND createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string pendingOrders = "0";

    if (!result.empty()) {
        pendingOrders = result[0]["pendingOrders"];
    }

    // refundRequests
    sql = "SELECT COUNT(*) AS refundRequests FROM asks WHERE status = 'pending' AND requestType = 'refundTicket' AND createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string refundRequests = "0";

    if (!result.empty()) {
        refundRequests = result[0]["refundRequests"];
    }

    // systemNotifications
    sql = "SELECT COUNT(*) AS systemNotifications FROM notifications WHERE createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string systemNotifications = "0";
    if (!result.empty()) {
        systemNotifications = result[0]["systemNotifications"];
    }

    // 使用新的JsonValue类型构建嵌套JSON
    std::map<std::string, JsonValue> data;
    data["todayRevenue"] = JsonValue(todayRevenue);
    data["todayOrders"] = JsonValue(todayOrders);
    data["activeUsers"] = JsonValue(activeUsers);
    data["pendingOrders"] = JsonValue(pendingOrders);
    data["refundRequests"] = JsonValue(refundRequests);
    data["systemNotifications"] = JsonValue(systemNotifications);

    std::map<std::string, JsonValue> resMp;
    resMp["data"] = JsonValue(data);

    res.success(resMp);
}

/**
 * @brief 获取票务列表（支持分页）
 * 
 * @param req 请求对象，包含查询参数：
 *            - page: 页码，从1开始（可选）
 *            - pageSize: 每页数量，最大100（可选）
 * @param res 响应对象，返回JSON格式：
 *            - message: 状态消息
 *            - status: 状态码
 *            - tickets: 票务数组，每个票务包含：
 *              - ticket_id: 票务ID
 *              - ticket_name: 票务名称
 *              - departure_location: 出发地
 *              - arrival_location: 目的地
 *              - departure_time: 出发时间
 *              - arrival_time: 到达时间
 *              - price: 价格
 *              - stock: 库存
 *              - train_number: 车次号
 *              - status: 状态（available/sold_out）
 *            - totalCount: 总记录数
 */
void getTickets(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    std::string page = req.query_param("page");
    std::string size = req.query_param("pageSize");
    
    // 默认值
    int pageNum = 1;
    int pageSize = 10;
    
    if (!page.empty()) {
        try {
            pageNum = std::stoi(page);
            if (pageNum < 1) pageNum = 1;
        } catch (...) {
            pageNum = 1;
        }
    }
    
    if (!size.empty()) {
        try {
            pageSize = std::stoi(size);
            if (pageSize < 1) pageSize = 10;
            if (pageSize > 100) pageSize = 100; // 最大100
        } catch (...) {
            pageSize = 10;
        }
    }
    
    int offset = (pageNum - 1) * pageSize;
    
    // 获取总数
    std::string countSql = "SELECT COUNT(*) AS total FROM tickets;";
    auto countResult = DBConnector::getInstance()->query(countSql);
    std::string totalCount = "0";
    if (!countResult.empty()) {
        totalCount = countResult[0]["total"];
    }
    
    // 获取票务列表
    std::string sql = "SELECT id AS ticket_id, name AS train_number, `from` AS departure_location, `to` AS arrival_location, "
                      "startTime AS departure_time, endTime AS arrival_time, price, cnt AS stock, type AS ticket_name, "
                      "CASE WHEN cnt > 0 THEN 'available' ELSE 'sold_out' END AS status "
                      "FROM tickets ORDER BY id DESC LIMIT " + std::to_string(pageSize) + " OFFSET " + std::to_string(offset) + ";";
    
    auto result = DBConnector::getInstance()->query(sql);
    
    // 构建响应
    std::vector<JsonValue> tickets;
    for (const auto& row : result) {
        std::map<std::string, JsonValue> ticket;
        if (row.count("ticket_id")) ticket["ticket_id"] = JsonValue(row.at("ticket_id"));
        if (row.count("ticket_name")) ticket["ticket_name"] = JsonValue(TicketsTypeToType(row.at("ticket_name")));
        if (row.count("departure_location")) ticket["departure_location"] = JsonValue(row.at("departure_location"));
        if (row.count("arrival_location")) ticket["arrival_location"] = JsonValue(row.at("arrival_location"));
        if (row.count("departure_time")) ticket["departure_time"] = JsonValue(row.at("departure_time"));
        if (row.count("arrival_time")) ticket["arrival_time"] = JsonValue(row.at("arrival_time"));
        if (row.count("price")) ticket["price"] = JsonValue(row.at("price"));
        if (row.count("stock")) ticket["stock"] = JsonValue(row.at("stock"));
        if (row.count("train_number")) ticket["train_number"] = JsonValue(row.at("train_number"));
        if (row.count("status")) ticket["status"] = JsonValue(row.at("status"));
        tickets.emplace_back(ticket);
    }
    
    std::map<std::string, JsonValue> resMp;
    resMp["tickets"] = JsonValue(tickets);
    resMp["totalCount"] = JsonValue(totalCount);
    resMp["message"] = JsonValue("Success");
    resMp["status"] = JsonValue("ok");
    
    res.json(toJson(resMp));
}

/**
 * @brief 添加新票务
 * 
 * @param req 请求对象，JSON body包含：
 *            - ticket_name: 票务名称（必填）
 *            - departure_location: 出发地（必填）
 *            - arrival_location: 目的地（必填）
 *            - departure_time: 出发时间（必填）
 *            - arrival_time: 到达时间（必填）
 *            - price: 价格（必填）
 *            - stock: 库存数量（必填）
 *            - train_number: 车次号（可选）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - success: 操作是否成功
 */
void addTickets(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        Ticket ticket;
        if (bodyJson.count("train_number")) ticket.name = bodyJson["train_number"];
        if (bodyJson.count("departure_location")) ticket.from = bodyJson["departure_location"];
        if (bodyJson.count("arrival_location")) ticket.to = bodyJson["arrival_location"];
        if (bodyJson.count("departure_time")) ticket.startTime = bodyJson["departure_time"];
        if (bodyJson.count("arrival_time")) ticket.endTime = bodyJson["arrival_time"];
        if (bodyJson.count("price")) ticket.price = bodyJson["price"];
        if (bodyJson.count("stock")) {
            try {
                ticket.cnt = std::stoi(bodyJson["stock"]);
            } catch (...) {
                ticket.cnt = 0;
            }
        }

        if (bodyJson.count("ticket_name")) {
            std::string type = bodyJson["ticket_type"];
            ticket.type = TypeToTicketsType(type+" "+bodyJson["ticket_name"]);
        }
        
        if (ticket.save()) {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("Ticket added successfully");
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        } else {
            res.error(400, "Failed to add ticket");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 更新票务信息
 * 
 * @param req 请求对象，JSON body包含：
 *            - ticket_id: 票务ID（必填）
 *            - ticket_name: 票务名称（可选）
 *            - departure_location: 出发地（可选）
 *            - arrival_location: 目的地（可选）
 *            - departure_time: 出发时间（可选）
 *            - arrival_time: 到达时间（可选）
 *            - price: 价格（可选）
 *            - stock: 库存数量（可选）
 *            - train_number: 车次号（可选）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - data.ticket_id: 更新的票务ID
 *            - success: 操作是否成功
 */
void updateTickets(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("ticket_id") || bodyJson["ticket_id"].empty()) {
            res.error(400, "ticket_id is required");
            return;
        }
        
        std::string ticketId = bodyJson["ticket_id"];
        
        // 构建UPDATE语句
        std::vector<std::string> updates;
        if (bodyJson.count("train_number") && !bodyJson["train_number"].empty()) {
            updates.push_back("name = '" + Model::escapeSqlLiteral(bodyJson["train_number"]) + "'");
        }
        if (bodyJson.count("departure_location") && !bodyJson["departure_location"].empty()) {
            updates.push_back("`from` = '" + Model::escapeSqlLiteral(bodyJson["departure_location"]) + "'");
        }
        if (bodyJson.count("arrival_location") && !bodyJson["arrival_location"].empty()) {
            updates.push_back("`to` = '" + Model::escapeSqlLiteral(bodyJson["arrival_location"]) + "'");
        }
        if (bodyJson.count("departure_time") && !bodyJson["departure_time"].empty()) {
            updates.push_back("startTime = '" + Model::escapeSqlLiteral(bodyJson["departure_time"]) + "'");
        }
        if (bodyJson.count("arrival_time") && !bodyJson["arrival_time"].empty()) {
            updates.push_back("endTime = '" + Model::escapeSqlLiteral(bodyJson["arrival_time"]) + "'");
        }
        if (bodyJson.count("price") && !bodyJson["price"].empty()) {
            updates.push_back("price = '" + Model::escapeSqlLiteral(bodyJson["price"]) + "'");
        }
        if (bodyJson.count("stock") && !bodyJson["stock"].empty()) {
            updates.push_back("cnt = " + bodyJson["stock"]);
        }
        if (bodyJson.count("ticket_name") && !bodyJson["ticket_name"].empty()) {
            std::string type = bodyJson["type"];
            updates.push_back("type = '" + TypeToTicketsType(type+" "+Model::escapeSqlLiteral(bodyJson["train_number"])) + "'");
        }
        
        if (updates.empty()) {
            res.error(400, "No fields to update");
            return;
        }
        
        std::string sql = "UPDATE tickets SET " + updates[0];
        for (size_t i = 1; i < updates.size(); i++) {
            sql += ", " + updates[i];
        }
        sql += " WHERE id = " + ticketId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            res.error(400, "Failed to update ticket");
        } else {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("Ticket updated successfully");
            data["ticket_id"] = JsonValue(ticketId);
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 删除票务
 * 
 * @param req 请求对象，JSON body包含：
 *            - ticket_id: 票务ID（必填）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - success: 操作是否成功
 */
void deleteTickets(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("ticket_id") || bodyJson["ticket_id"].empty()) {
            res.error(400, "ticket_id is required");
            return;
        }
        
        std::string ticketId = bodyJson["ticket_id"];
        std::string sql = "DELETE FROM tickets WHERE id = " + ticketId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            res.error(400, "Failed to delete ticket");
        } else {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("Ticket deleted successfully");
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 搜索票务
 * 
 * @param req 请求对象，查询参数包含：
 *            - search: 搜索关键词（票务ID或名称）（可选）
 *            - searchType:
 * @param res 响应对象，返回JSON格式：
 *            - message: 状态消息
 *            - success: 操作是否成功
 *            - tickets: 票务数组，每个票务包含：
 *              - ticket_id: 票务ID
 *              - ticket_name: 票务名称
 *              - departure_location: 出发地
 *              - arrival_location: 目的地
 *              - departure_time: 出发时间
 *              - arrival_time: 到达时间
 *              - price: 价格
 *              - stock: 库存
 *              - train_number: 车次号
 *              - status: 状态
 *            - totalCount: 总记录数
 */
void searchTickets(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    std::string search = req.query_param("search");
    std::string type = req.query_param("searchType");

    std::string typeCondtion;
    if (type=="Train") {
        typeCondtion = "( 'HighFirstClass', 'HighSecondClass', 'QuickFirstClass', 'QuickSecondClass', 'SoftBed', 'HardBed', 'SoftSeat', 'HardSeat', 'NoSeat' )";
    } else if (type=="Plane") {
        typeCondtion = "( 'FlyFirstClass', 'FlyEconomyClass' )";
    } else if(type=="Car") {
        typeCondtion = "( 'CarSeat' )";
    }
    
    std::string sql = "SELECT id AS ticket_id, name AS ticket_name, `from` AS departure_location, `to` AS arrival_location, "
                      "startTime AS departure_time, endTime AS arrival_time, price, cnt AS stock, type AS train_number, "
                      "CASE WHEN cnt > 0 THEN 'available' ELSE 'sold_out' END AS status "
                      "FROM tickets WHERE type IN " + typeCondtion;
    
    if (!search.empty()) {
        sql += " AND (id LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR name LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR type LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR `from` LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR `to` LIKE '%" + Model::escapeSqlLiteral(search) + "%')";
    }
    
    sql += " ORDER BY id DESC;";

//    std::cout<<sql<<std::endl;
    
    auto result = DBConnector::getInstance()->query(sql);
    
    // 获取总数
    std::string countSql = "SELECT COUNT(*) AS total FROM tickets WHERE 1=1";
    if (!search.empty()) {
        countSql += " AND (id LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR name LIKE '%" + Model::escapeSqlLiteral(search) + "%')";
    }
    countSql += ";";
    
    auto countResult = DBConnector::getInstance()->query(countSql);
    std::string totalCount = "0";
    if (!countResult.empty()) {
        totalCount = countResult[0]["total"];
    }
    
    // 构建响应
    std::vector<JsonValue> tickets;
    for (const auto& row : result) {
        std::map<std::string, JsonValue> ticket;
        if (row.count("ticket_id")) ticket["ticket_id"] = JsonValue(row.at("ticket_id"));
        if (row.count("train_number")) ticket["ticket_name"] = JsonValue(TicketsTypeToType(row.at("train_number")));
        if (row.count("departure_location")) ticket["departure_location"] = JsonValue(row.at("departure_location"));
        if (row.count("arrival_location")) ticket["arrival_location"] = JsonValue(row.at("arrival_location"));
        if (row.count("departure_time")) ticket["departure_time"] = JsonValue(row.at("departure_time"));
        if (row.count("arrival_time")) ticket["arrival_time"] = JsonValue(row.at("arrival_time"));
        if (row.count("price")) ticket["price"] = JsonValue(row.at("price"));
        if (row.count("stock")) ticket["stock"] = JsonValue(row.at("stock"));
        if (row.count("ticket_name")) {
            ticket["train_number"] = JsonValue(row.at("ticket_name"));
//            std::cout<<row.at("ticket_name")<<' '<<TicketsTypeToType(row.at("ticket_name")) << std::endl;
        }
        if (row.count("status")) ticket["status"] = JsonValue(row.at("status"));
        tickets.push_back(JsonValue(ticket));
    }
    
    std::map<std::string, JsonValue> resMp;
    resMp["tickets"] = JsonValue(tickets);
    resMp["totalCount"] = JsonValue(totalCount);
    resMp["message"] = JsonValue("Success");
    resMp["success"] = JsonValue(true);
    
    res.json(toJson(resMp));
}
/**
 * @brief 获取订单列表
 * 
 * @param req 请求对象（当前未使用分页参数）
 * @param res 响应对象，返回JSON格式：
 *            - data.orders: 订单数组，每个订单包含：
 *              - order_id: 订单ID
 *              - status: 订单状态
 *              - amount: 金额
 *              - ticket_id: 票务ID
 *              - ticket_type: 票务类型
 *              - departure_location: 出发地
 *              - arrival_location: 目的地
 *              - departure_time: 出发时间
 *              - arrival_time: 到达时间
 *              - username: 用户名
 *            - data.pagination: 分页信息
 *              - currentPage: 当前页码
 *              - pageSize: 每页大小
 *              - totalItems: 总记录数
 *              - totalPages: 总页数
 *            - success: 操作是否成功
 */
void getOrders(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    std::string sql = "SELECT o.id AS order_id, o.status, o.totalPrice AS amount, o.ticketId, o.quantity, "
                      "t.name AS ticket_name, t.`from` AS departure_location, t.`to` AS arrival_location, "
                      "t.startTime AS departure_time, t.endTime AS arrival_time, t.type AS ticket_type, "
                      "u.name AS username "
                      "FROM orders o "
                      "LEFT JOIN tickets t ON o.ticketId = t.id "
                      "LEFT JOIN users u ON o.userId = u.id "
                      "ORDER BY o.id DESC;";
    
    auto result = DBConnector::getInstance()->query(sql);
    
    // 构建响应
    std::vector<JsonValue> orders;
    for (const auto& row : result) {
        std::map<std::string, JsonValue> order;
        if (row.count("order_id")) order["order_id"] = JsonValue(row.at("order_id"));
        if (row.count("status")) order["status"] = JsonValue(row.at("status"));
        if (row.count("amount")) order["amount"] = JsonValue(row.at("amount"));
        if (row.count("ticketId")) order["ticket_id"] = JsonValue(row.at("ticketId"));
        if (row.count("ticket_type")) order["ticket_type"] = JsonValue(row.at("ticket_type"));
        if (row.count("departure_location")) order["departure_location"] = JsonValue(row.at("departure_location"));
        if (row.count("arrival_location")) order["arrival_location"] = JsonValue(row.at("arrival_location"));
        if (row.count("departure_time")) order["departure_time"] = JsonValue(row.at("departure_time"));
        if (row.count("arrival_time")) order["arrival_time"] = JsonValue(row.at("arrival_time"));
        if (row.count("username")) order["username"] = JsonValue(row.at("username"));
        orders.push_back(JsonValue(order));
    }
    
    // 分页信息（虽然注释说用不上，但为了完整性还是加上）
    std::map<std::string, JsonValue> pagination;
    pagination["currentPage"] = JsonValue(1);
    pagination["pageSize"] = JsonValue(static_cast<int>(orders.size()));
    pagination["totalItems"] = JsonValue(static_cast<int>(orders.size()));
    pagination["totalPages"] = JsonValue(1);
    
    std::map<std::string, JsonValue> data;
    data["orders"] = JsonValue(orders);
    data["pagination"] = JsonValue(pagination);
    
    std::map<std::string, JsonValue> resMp;
    resMp["data"] = JsonValue(data);
    resMp["success"] = JsonValue(true);
    
    res.success(resMp);
}
/**
 * @brief 更新订单状态
 * 
 * @param req 请求对象，JSON body包含：
 *            - order_id: 订单ID（必填）
 *            - status: 订单状态（必填）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - data.order_id: 订单ID
 *            - data.status: 更新后的状态
 *            - success: 操作是否成功
 */
void updateOrders(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("order_id") || bodyJson["order_id"].empty()) {
            res.error(400, "order_id is required");
            return;
        }
        
        if (!bodyJson.count("status") || bodyJson["status"].empty()) {
            res.error(400, "status is required");
            return;
        }
        
        std::string orderId = bodyJson["order_id"];
        std::string status = bodyJson["status"];
        
        std::string sql = "UPDATE orders SET status = '" + Model::escapeSqlLiteral(status) + "' WHERE id = " + orderId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            res.error(400, "Failed to update order");
        } else {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("Order updated successfully");
            data["order_id"] = JsonValue(orderId);
            data["status"] = JsonValue(status);
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 删除订单
 * 
 * @param req 请求对象，JSON body包含：
 *            - order_id: 订单ID（必填）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - data.order_id: 删除的订单ID
 *            - success: 操作是否成功
 */
void deleteOrders(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("order_id") || bodyJson["order_id"].empty()) {
            res.error(400, "order_id is required");
            return;
        }
        
        std::string orderId = bodyJson["order_id"];
        std::string sql = "DELETE FROM orders WHERE id = " + orderId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            res.error(400, "Failed to delete order");
        } else {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("Order deleted successfully");
            data["order_id"] = JsonValue(orderId);
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 搜索用户订单
 * 
 * @param req 请求对象，JSON body包含：
 *            - dateFilter: 日期筛选（today/week/month）（可选）
 *            - searchText: 搜索关键词（可选）
 *            - status: 订单状态筛选（可选）
 * @param res 响应对象，返回JSON格式：
 *            - data.orders: 订单数组，每个订单包含：
 *              - order_id: 订单ID
 *              - status: 订单状态
 *              - amount: 金额
 *              - ticket_id: 票务ID
 *              - ticket_type: 票务类型
 *              - departure_location: 出发地
 *              - arrival_location: 目的地
 *              - departure_time: 出发时间
 *              - arrival_time: 到达时间
 *              - username: 用户名
 *            - data.pagination: 分页信息
 *            - data.totalCount: 总记录数
 *            - success: 操作是否成功
 */
void searchUsersOrders(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        std::string dateFilter = bodyJson.count("dateFilter") ? bodyJson["dateFilter"] : "";
        std::string searchText = bodyJson.count("searchText") ? bodyJson["searchText"] : "";
        std::string status = bodyJson.count("status") ? bodyJson["status"] : "";
        
        std::string today = getToday();
        std::string startDate = today;
        std::string endDate = addDay(today, 1);
        
        // 处理日期筛选
        if (dateFilter == "week") {
            startDate = addDay(today, -7);
        } else if (dateFilter == "month") {
            startDate = addDay(today, -30);
        }
        
        std::string sql = "SELECT o.id AS order_id, o.status, o.totalPrice AS amount, o.ticketId, o.quantity, "
                          "t.name AS ticket_name, t.`from` AS departure_location, t.`to` AS arrival_location, "
                          "t.startTime AS departure_time, t.endTime AS arrival_time, t.type AS ticket_type, "
                          "u.name AS username "
                          "FROM orders o "
                          "LEFT JOIN tickets t ON o.ticketId = t.id "
                          "LEFT JOIN users u ON o.userId = u.id "
                          "WHERE o.createdAt BETWEEN '" + startDate + "' AND '" + endDate + "'";
        
        if (!status.empty()) {
            sql += " AND o.status = '" + Model::escapeSqlLiteral(status) + "'";
        }
        
        if (!searchText.empty()) {
            sql += " AND (o.id LIKE '%" + Model::escapeSqlLiteral(searchText) + "%' OR u.name LIKE '%" + Model::escapeSqlLiteral(searchText) + "%' OR t.name LIKE '%" + Model::escapeSqlLiteral(searchText) + "%')";
        }
        
        sql += " ORDER BY o.id DESC;";
        
        auto result = DBConnector::getInstance()->query(sql);
        
        // 获取总数
        std::string countSql = "SELECT COUNT(*) AS total FROM orders o "
                               "LEFT JOIN tickets t ON o.ticketId = t.id "
                               "LEFT JOIN users u ON o.userId = u.id "
                               "WHERE o.createdAt BETWEEN '" + startDate + "' AND '" + endDate + "'";
        
        if (!status.empty()) {
            countSql += " AND o.status = '" + Model::escapeSqlLiteral(status) + "'";
        }
        
        if (!searchText.empty()) {
            countSql += " AND (o.id LIKE '%" + Model::escapeSqlLiteral(searchText) + "%' OR u.name LIKE '%" + Model::escapeSqlLiteral(searchText) + "%' OR t.name LIKE '%" + Model::escapeSqlLiteral(searchText) + "%')";
        }
        countSql += ";";
        
        auto countResult = DBConnector::getInstance()->query(countSql);
        std::string totalCount = "0";
        if (!countResult.empty()) {
            totalCount = countResult[0]["total"];
        }
        
        // 构建响应
        std::vector<JsonValue> orders;
        for (const auto& row : result) {
            std::map<std::string, JsonValue> order;
            if (row.count("order_id")) order["order_id"] = JsonValue(row.at("order_id"));
            if (row.count("status")) order["status"] = JsonValue(row.at("status"));
            if (row.count("amount")) order["amount"] = JsonValue(row.at("amount"));
            if (row.count("ticketId")) order["ticket_id"] = JsonValue(row.at("ticketId"));
            if (row.count("ticket_type")) order["ticket_type"] = JsonValue(row.at("ticket_type"));
            if (row.count("departure_location")) order["departure_location"] = JsonValue(row.at("departure_location"));
            if (row.count("arrival_location")) order["arrival_location"] = JsonValue(row.at("arrival_location"));
            if (row.count("departure_time")) order["departure_time"] = JsonValue(row.at("departure_time"));
            if (row.count("arrival_time")) order["arrival_time"] = JsonValue(row.at("arrival_time"));
            if (row.count("username")) order["username"] = JsonValue(row.at("username"));
            orders.push_back(JsonValue(order));
        }
        
        // 分页信息
        std::map<std::string, JsonValue> pagination;
        pagination["currentPage"] = JsonValue(1);
        pagination["pageSize"] = JsonValue(static_cast<int>(orders.size()));
        pagination["totalItems"] = JsonValue(std::stoi(totalCount));
        pagination["totalPages"] = JsonValue(1);
        
        std::map<std::string, JsonValue> data;
        data["orders"] = JsonValue(orders);
        data["pagination"] = JsonValue(pagination);
        data["totalCount"] = JsonValue(totalCount);
        
        std::map<std::string, JsonValue> resMp;
        resMp["data"] = JsonValue(data);
        resMp["success"] = JsonValue(true);
        
        res.success(resMp);
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 获取订单统计信息
 * 
 * @param req 请求对象（无参数）
 * @param res 响应对象，返回JSON格式：
 *            - data.totalOrders: 总订单数
 *            - data.totalRevenue: 总收入
 *            - data.todayOrders: 今日订单数
 *            - data.todayRevenue: 今日收入
 *            - data.pendingOrders: 待处理订单数
 *            - data.completedOrders: 已完成订单数
 *            - data.cancelledOrders: 已取消订单数
 *            - success: 操作是否成功
 */
void getOrdersStatistics(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    std::string today = getToday();
    std::string tomorrow = addDay(today, 1);
    
    // TotalOrders
    std::string sql = "SELECT COUNT(*) AS total FROM orders;";
    auto result = DBConnector::getInstance()->query(sql);
    std::string totalOrders = "0";
    if (!result.empty()) {
        totalOrders = result[0]["total"];
    }
    
    // TotalRevenue
    sql = "SELECT SUM(CAST(totalPrice AS DECIMAL(10,2))) AS total FROM orders;";
    result = DBConnector::getInstance()->query(sql);
    std::string totalRevenue = "0.00";
    if (!result.empty() && !result[0]["total"].empty() && result[0]["total"] != "NULL") {
        totalRevenue = result[0]["total"];
    }
    
    // TodayOrders
    sql = "SELECT COUNT(*) AS total FROM orders WHERE createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string todayOrders = "0";
    if (!result.empty()) {
        todayOrders = result[0]["total"];
    }
    
    // TodayRevenue
    sql = "SELECT SUM(CAST(totalPrice AS DECIMAL(10,2))) AS total FROM orders WHERE createdAt BETWEEN '" + today + "' AND '" + tomorrow + "';";
    result = DBConnector::getInstance()->query(sql);
    std::string todayRevenue = "0.00";
    if (!result.empty() && !result[0]["total"].empty() && result[0]["total"] != "NULL") {
        todayRevenue = result[0]["total"];
    }
    
    // PendingOrders
    sql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'ordered';";
    result = DBConnector::getInstance()->query(sql);
    std::string pendingOrders = "0";
    if (!result.empty()) {
        pendingOrders = result[0]["total"];
    }
    
    // CompletedOrders
    sql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'finished';";
    result = DBConnector::getInstance()->query(sql);
    std::string completedOrders = "0";
    if (!result.empty()) {
        completedOrders = result[0]["total"];
    }
    
    // CancelledOrders
    sql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'cancelled';";
    result = DBConnector::getInstance()->query(sql);
    std::string cancelledOrders = "0";
    if (!result.empty()) {
        cancelledOrders = result[0]["total"];
    }
    
    std::map<std::string, JsonValue> data;
    data["totalOrders"] = JsonValue(totalOrders);
    data["totalRevenue"] = JsonValue(totalRevenue);
    data["todayOrders"] = JsonValue(todayOrders);
    data["todayRevenue"] = JsonValue(todayRevenue);
    data["pendingOrders"] = JsonValue(pendingOrders);
    data["completedOrders"] = JsonValue(completedOrders);
    data["cancelledOrders"] = JsonValue(cancelledOrders);
    
    std::map<std::string, JsonValue> resMp;
    resMp["data"] = JsonValue(data);
    resMp["success"] = JsonValue(true);
    
    res.success(resMp);
}
/**
 * @brief 获取用户列表
 * 
 * @param req 请求对象（无参数）
 * @param res 响应对象，返回JSON格式：
 *            - users: 用户数组，每个用户包含：
 *              - user_id: 用户ID
 *              - name: 用户名
 *              - email: 邮箱
 *              - phone: 手机号
 *              - status: 状态
 *            - total: 总用户数
 *            - success: 操作是否成功
 */
void getUsers(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    std::string sql = "SELECT id AS user_id, name, email, '' AS phone, role AS status FROM users ORDER BY id DESC;";
    
    auto result = DBConnector::getInstance()->query(sql);
    
    // 获取总数
    std::string countSql = "SELECT COUNT(*) AS total FROM users;";
    auto countResult = DBConnector::getInstance()->query(countSql);
    std::string total = "0";
    if (!countResult.empty()) {
        total = countResult[0]["total"];
    }
    
    // 构建响应
    std::vector<JsonValue> users;
    for (const auto& row : result) {
        std::map<std::string, JsonValue> user;
        if (row.count("user_id")) user["user_id"] = JsonValue(row.at("user_id"));
        if (row.count("name")) user["name"] = JsonValue(row.at("name"));
        if (row.count("email")) user["email"] = JsonValue(row.at("email"));
        if (row.count("phone")) user["phone"] = JsonValue(row.at("phone"));
        if (row.count("status")) user["status"] = JsonValue(row.at("status"));
        users.push_back(JsonValue(user));
    }
    
    std::map<std::string, JsonValue> resMp;
    resMp["users"] = JsonValue(users);
    resMp["total"] = JsonValue(total);
    resMp["success"] = JsonValue(true);
    
    res.json(toJson(resMp));
}
/**
 * @brief 搜索用户
 * 
 * @param req 请求对象，JSON body包含：
 *            - search: 搜索关键词（用户名、姓名、手机号、邮箱、状态）（必填）
 * @param res 响应对象，返回JSON格式：
 *            - users: 用户数组，每个用户包含：
 *              - id: 用户ID
 *              - name: 用户名
 *              - email: 邮箱
 *              - phone: 手机号
 *              - status: 状态
 *            - total: 总用户数
 *            - success: 操作是否成功
 */
void searchUsers(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        std::string search = bodyJson.count("search") ? bodyJson["search"] : "";
        
        std::string sql = "SELECT id AS user_id, name, email, '' AS phone, role AS status FROM users WHERE 1=1";
        
        if (!search.empty()) {
            sql += " AND (id LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR name LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR email LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR role LIKE '%" + Model::escapeSqlLiteral(search) + "%')";
        }
        
        sql += " ORDER BY id DESC;";
        
        auto result = DBConnector::getInstance()->query(sql);
        
        // 获取总数
        std::string countSql = "SELECT COUNT(*) AS total FROM users WHERE 1=1";
        if (!search.empty()) {
            countSql += " AND (id LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR name LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR email LIKE '%" + Model::escapeSqlLiteral(search) + "%' OR role LIKE '%" + Model::escapeSqlLiteral(search) + "%')";
        }
        countSql += ";";
        
        auto countResult = DBConnector::getInstance()->query(countSql);
        std::string total = "0";
        if (!countResult.empty()) {
            total = countResult[0]["total"];
        }
        
        // 构建响应
        std::vector<JsonValue> users;
        for (const auto& row : result) {
            std::map<std::string, JsonValue> user;
            if (row.count("user_id")) user["id"] = JsonValue(row.at("user_id"));
            if (row.count("name")) user["name"] = JsonValue(row.at("name"));
            if (row.count("email")) user["email"] = JsonValue(row.at("email"));
            if (row.count("phone")) user["phone"] = JsonValue(row.at("phone"));
            if (row.count("status")) user["status"] = JsonValue(row.at("status"));
            users.push_back(JsonValue(user));
        }
        
        std::map<std::string, JsonValue> resMp;
        resMp["users"] = JsonValue(users);
        resMp["total"] = JsonValue(total);
        resMp["success"] = JsonValue(true);
        
        res.json(toJson(resMp));
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 获取用户统计信息
 * 
 * @param req 请求对象（无参数）
 * @param res 响应对象，返回JSON格式：
 *            - data.totalUsers: 总用户数
 *            - data.normalUsers: 正常用户数
 *            - data.frozenUsers: 冻结用户数
 *            - success: 操作是否成功
 */
void getUsersStatistics(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    // TotalUsers
    std::string sql = "SELECT COUNT(*) AS total FROM users;";
    auto result = DBConnector::getInstance()->query(sql);
    std::string totalUsers = "0";
    if (!result.empty()) {
        totalUsers = result[0]["total"];
    }
    
    // NormalUsers (假设role为'user'的是正常用户)
    sql = "SELECT COUNT(*) AS total FROM users WHERE role = 'user';";
    result = DBConnector::getInstance()->query(sql);
    std::string normalUsers = "0";
    if (!result.empty()) {
        normalUsers = result[0]["total"];
    }
    
    // FrozenUsers (假设status字段或特定role表示冻结，这里用role='frozen'作为示例)
    // 如果没有frozen字段，可以根据实际业务逻辑调整
    sql = "SELECT COUNT(*) AS total FROM users WHERE role = 'frozen';";
    result = DBConnector::getInstance()->query(sql);
    std::string frozenUsers = "0";
    if (!result.empty()) {
        frozenUsers = result[0]["total"];
    }
    
    std::map<std::string, JsonValue> data;
    data["totalUsers"] = JsonValue(totalUsers);
    data["normalUsers"] = JsonValue(normalUsers);
    data["frozenUsers"] = JsonValue(frozenUsers);
    
    std::map<std::string, JsonValue> resMp;
    resMp["data"] = JsonValue(data);
    resMp["success"] = JsonValue(true);
    
    res.success(resMp);
}
/**
 * @brief 获取用户详情
 * 
 * @param req 请求对象，查询参数包含：
 *            - user_id: 用户ID（必填）
 * @param res 响应对象，返回JSON格式：
 *            - user: 用户信息，包含：
 *              - user_id: 用户ID
 *              - name: 用户名
 *              - email: 邮箱
 *              - phone: 手机号
 *              - status: 状态
 *            - success: 操作是否成功
 */
void getUsersDetail(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    std::string userId = req.query_param("user_id");
    
    if (userId.empty()) {
        res.error(400, "user_id is required");
        return;
    }
    
    std::string sql = "SELECT id AS user_id, name, email, '' AS phone, role AS status FROM users WHERE id = " + userId + ";";
    
    auto result = DBConnector::getInstance()->query(sql);
    
    if (result.empty()) {
        res.error(404, "User not found");
        return;
    }
    
    std::map<std::string, JsonValue> user;
    if (result[0].count("user_id")) user["user_id"] = JsonValue(result[0].at("user_id"));
    if (result[0].count("name")) user["name"] = JsonValue(result[0].at("name"));
    if (result[0].count("email")) user["email"] = JsonValue(result[0].at("email"));
    if (result[0].count("phone")) user["phone"] = JsonValue(result[0].at("phone"));
    if (result[0].count("status")) user["status"] = JsonValue(result[0].at("status"));
    
    std::map<std::string, JsonValue> resMp;
    resMp["user"] = JsonValue(user);
    resMp["success"] = JsonValue(true);
    
    res.json(toJson(resMp));
}
/**
 * @brief 冻结用户
 * 
 * @param req 请求对象，JSON body包含：
 *            - user_id: 用户ID（必填）
 * @param res 响应对象，返回JSON格式：
 *            - user: 用户信息
 *              - user_id: 用户ID
 *              - name: 用户名
 *              - email: 邮箱
 *              - phone: 手机号
 *              - status: 状态（frozen）
 *            - success: 操作是否成功
 */
void freezeUser(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("user_id") || bodyJson["user_id"].empty()) {
            res.error(400, "user_id is required");
            return;
        }
        
        std::string userId = bodyJson["user_id"];
        
        // 更新用户状态为冻结（假设通过role或status字段，这里用role='frozen'作为示例）
        std::string sql = "UPDATE users SET role = 'frozen' WHERE id = " + userId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            res.error(400, "Failed to freeze user");
        } else {
            std::map<std::string, JsonValue> user;
            user["user_id"] = JsonValue(userId);
            user["name"] = JsonValue("");
            user["email"] = JsonValue("");
            user["phone"] = JsonValue("");
            user["status"] = JsonValue("frozen");
            
            std::map<std::string, JsonValue> resMp;
            resMp["user"] = JsonValue(user);
            resMp["success"] = JsonValue(true);
            
            res.json(toJson(resMp));
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 解冻用户
 * 
 * @param req 请求对象，JSON body包含：
 *            - user_id: 用户ID（必填）
 * @param res 响应对象，返回JSON格式：
 *            - data.message: 操作结果消息
 *            - data.status: 更新后的状态
 *            - data.user_id: 用户ID
 *            - error: 错误信息（如果失败）
 *            - success: 操作是否成功
 */
void unfreezeUser(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson = req.queryParams;
        
        if (!bodyJson.count("user_id") || bodyJson["user_id"].empty()) {
            res.error(400, "user_id is required");
            return;
        }
        
        std::string userId = bodyJson["user_id"];
        
        // 更新用户状态为正常（恢复为user角色）
        std::string sql = "UPDATE users SET role = 'user' WHERE id = " + userId + ";";
        
        int executeCode = DBConnector::getInstance()->execute(sql);
        if (executeCode == -1) {
            std::map<std::string, JsonValue> resMp;
            resMp["error"] = JsonValue("Failed to unfreeze user");
            resMp["success"] = JsonValue(false);
            res.json(toJson(resMp));
        } else {
            std::map<std::string, JsonValue> data;
            data["message"] = JsonValue("User unfrozen successfully");
            data["status"] = JsonValue("user");
            data["user_id"] = JsonValue(userId);
            
            std::map<std::string, JsonValue> resMp;
            resMp["data"] = JsonValue(data);
            resMp["success"] = JsonValue(true);
            
            res.success(resMp);
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 获取综合统计数据
 * 
 * @param req 请求对象，JSON body包含：
 *            - timeRange: 时间范围（可选），可选值：
 *              - today: 今天
 *              - yesterday: 昨天
 *              - this_week: 本周
 *              - last_week: 上周
 *              - this_month: 本月
 *              - last_month: 上月
 *              - this_year: 今年
 *              - last_year: 去年
 * @param res 响应对象，返回JSON格式：
 *            - data.totalRevenue: 总收入
 *            - data.totalOrders: 总订单数
 *            - data.totalTickets: 总票务数
 *            - data.activeUsers: 活跃用户数
 *            - data.categoryData: 分类数据数组
 *              - category: 分类名称
 *              - count: 数量
 *              - percentage: 百分比
 *              - revenue: 收入
 *            - data.revenueData: 收入数据数组
 *              - date: 日期
 *              - revenue: 收入
 *              - orders: 订单数
 *              - average_order_value: 平均订单价值
 *            - message: 状态消息
 *            - success: 操作是否成功
 */
void getStatistics(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson;
        if (!req.body.empty()) {
            bodyJson = req.queryParams;
        }
        
        std::string timeRange = bodyJson.count("timeRange") ? bodyJson["timeRange"] : "today";
        
        std::string today = getToday();
        std::string startDate = today;
        std::string endDate = addDay(today, 1);
        
        // 处理时间范围
        if (timeRange == "yesterday") {
            startDate = addDay(today, -1);
            endDate = today;
        } else if (timeRange == "this_week") {
            startDate = addDay(today, -7);
        } else if (timeRange == "last_week") {
            startDate = addDay(today, -14);
            endDate = addDay(today, -7);
        } else if (timeRange == "this_month") {
            startDate = addDay(today, -30);
        } else if (timeRange == "last_month") {
            startDate = addDay(today, -60);
            endDate = addDay(today, -30);
        } else if (timeRange == "this_year") {
            startDate = addDay(today, -365);
        } else if (timeRange == "last_year") {
            startDate = addDay(today, -730);
            endDate = addDay(today, -365);
        }
        
        // TotalRevenue
        std::string sql = "SELECT SUM(CAST(totalPrice AS DECIMAL(10,2))) AS total FROM orders WHERE createdAt BETWEEN '" + startDate + "' AND '" + endDate + "';";
        auto result = DBConnector::getInstance()->query(sql);
        std::string totalRevenue = "0.00";
        if (!result.empty() && !result[0]["total"].empty() && result[0]["total"] != "NULL") {
            totalRevenue = result[0]["total"];
        }
        
        // TotalOrders
        sql = "SELECT COUNT(*) AS total FROM orders WHERE createdAt BETWEEN '" + startDate + "' AND '" + endDate + "';";
        result = DBConnector::getInstance()->query(sql);
        std::string totalOrders = "0";
        if (!result.empty()) {
            totalOrders = result[0]["total"];
        }
        
        // TotalTickets
        sql = "SELECT COUNT(*) AS total FROM tickets;";
        result = DBConnector::getInstance()->query(sql);
        std::string totalTickets = "0";
        if (!result.empty()) {
            totalTickets = result[0]["total"];
        }
        
        // ActiveUsers
        sql = "SELECT COUNT(DISTINCT userId) AS total FROM browses WHERE browseTime BETWEEN '" + startDate + "' AND '" + endDate + "';";
        result = DBConnector::getInstance()->query(sql);
        std::string activeUsers = "0";
        if (!result.empty()) {
            activeUsers = result[0]["total"];
        }
        
        // CategoryData (按票务类型统计)
        sql = "SELECT t.type AS category, COUNT(*) AS count, SUM(CAST(o.totalPrice AS DECIMAL(10,2))) AS revenue "
              "FROM orders o JOIN tickets t ON o.ticketId = t.id "
              "WHERE o.createdAt BETWEEN '" + startDate + "' AND '" + endDate + "' "
              "GROUP BY t.type;";
        result = DBConnector::getInstance()->query(sql);
        
        std::vector<JsonValue> categoryData;
        double totalRev = std::stod(totalRevenue);
        for (const auto& row : result) {
            std::map<std::string, JsonValue> category;
            if (row.count("category")) category["category"] = JsonValue(row.at("category"));
            if (row.count("count")) category["count"] = JsonValue(row.at("count"));
            if (row.count("revenue")) category["revenue"] = JsonValue(row.at("revenue"));
            
            // 计算百分比
            if (totalRev > 0 && row.count("revenue") && !row.at("revenue").empty() && row.at("revenue") != "NULL") {
                double catRev = std::stod(row.at("revenue"));
                double percentage = (catRev / totalRev) * 100.0;
                category["percentage"] = JsonValue(std::to_string(percentage));
            } else {
                category["percentage"] = JsonValue("0.00");
            }
            
            categoryData.push_back(JsonValue(category));
        }
        
        // RevenueData (按日期统计，简化版，返回单条记录)
        std::vector<JsonValue> revenueData;
        std::map<std::string, JsonValue> revenue;
        revenue["date"] = JsonValue(today);
        revenue["revenue"] = JsonValue(totalRevenue);
        revenue["orders"] = JsonValue(totalOrders);
        if (std::stoi(totalOrders) > 0 && totalRev > 0) {
            revenue["average_order_value"] = JsonValue(std::to_string(totalRev / std::stoi(totalOrders)));
        } else {
            revenue["average_order_value"] = JsonValue("0.00");
        }
        revenueData.push_back(JsonValue(revenue));
        
        std::map<std::string, JsonValue> data;
        data["totalRevenue"] = JsonValue(totalRevenue);
        data["totalOrders"] = JsonValue(totalOrders);
        data["totalTickets"] = JsonValue(totalTickets);
        data["activeUsers"] = JsonValue(activeUsers);
        data["categoryData"] = JsonValue(categoryData);
        data["revenueData"] = JsonValue(revenueData);
        
        std::map<std::string, JsonValue> resMp;
        resMp["data"] = JsonValue(data);
        resMp["message"] = JsonValue("Success");
        resMp["success"] = JsonValue(true);
        
        res.json(toJson(resMp));
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 获取详细统计数据
 * 
 * @param req 请求对象，JSON body包含：
 *            - timeRange: 时间范围（可选），可选值：
 *              - today: 今天
 *              - yesterday: 昨天
 *              - this_week: 本周
 *              - last_week: 上周
 *              - this_month: 本月
 *              - last_month: 上月
 *              - this_year: 今年
 *              - last_year: 去年
 *            - limit: 返回记录数量限制，建议不超过1000（可选）
 * @param res 响应对象，返回JSON格式：
 *            - details: 详细数据数组，每个元素包含：
 *              - date: 日期
 *              - orders: 订单数
 *              - revenue: 收入
 *              - tickets: 票务数
 *              - users: 用户数
 *            - message: 状态消息
 *            - success: 操作是否成功
 */
void getStatisticsDetails(const Request& req, Response& res) {
    if (!Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        std::map<std::string, std::string> bodyJson;
        if (!req.body.empty()) {
            bodyJson = req.queryParams;
        }

        std::string timeRange = bodyJson.count("timeRange") ? bodyJson["timeRange"] : "today";
        int limit = 100;
        if (bodyJson.count("limit") && !bodyJson["limit"].empty()) {
            try {
                limit = std::stoi(bodyJson["limit"]);
                if (limit > 1000) limit = 1000;
            } catch (...) {
                limit = 100;
            }
        }

        std::string today = getToday();
        std::string startDate = today;
        std::string endDate = addDay(today, 1);

        // 处理时间范围
        if (timeRange == "yesterday") {
            startDate = addDay(today, -1);
            endDate = today;
        } else if (timeRange == "this_week") {
            startDate = addDay(today, -7);
        } else if (timeRange == "last_week") {
            startDate = addDay(today, -14);
            endDate = addDay(today, -7);
        } else if (timeRange == "this_month") {
            startDate = addDay(today, -30);
        } else if (timeRange == "last_month") {
            startDate = addDay(today, -60);
            endDate = addDay(today, -30);
        } else if (timeRange == "this_year") {
            startDate = addDay(today, -365);
        } else if (timeRange == "last_year") {
            startDate = addDay(today, -730);
            endDate = addDay(today, -365);
        }

        // 按日期统计（简化版，返回单条记录）
        std::string sql = "SELECT DATE(createdAt) AS date, COUNT(*) AS orders, "
                          "SUM(CAST(totalPrice AS DECIMAL(10,2))) AS revenue "
                          "FROM orders WHERE createdAt BETWEEN '" + startDate + "' AND '" + endDate + "' "
                                                                                                      "GROUP BY DATE(createdAt) ORDER BY date DESC LIMIT " +
                          std::to_string(limit) + ";";

        auto result = DBConnector::getInstance()->query(sql);

        std::vector<JsonValue> details;
        for (const auto &row: result) {
            std::map<std::string, JsonValue> detail;
            if (row.count("date")) detail["date"] = JsonValue(row.at("date"));
            if (row.count("orders")) detail["orders"] = JsonValue(row.at("orders"));
            if (row.count("revenue")) detail["revenue"] = JsonValue(row.at("revenue"));

            // Tickets (该日期的票务数量，简化处理)
            detail["tickets"] = JsonValue("0");

            // Users (该日期的活跃用户数)
            detail["users"] = JsonValue("0");

            details.push_back(JsonValue(detail));
        }

        std::map<std::string, JsonValue> resMp;
        resMp["details"] = JsonValue(details);
        resMp["message"] = JsonValue("Success");
        resMp["success"] = JsonValue(true);

        res.json(toJson(resMp));
    } catch (const std::exception &e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}

/**
 * @brief 获取收入图表数据
 *
 * @param req 请求对象，JSON body包含：
 *            - timeRange: 时间范围（可选），可选值：
 *              - today: 今天
 *              - yesterday: 昨天
 *              - this_week: 本周
 *              - last_week: 上周
 *              - this_month: 本月
 *              - last_month: 上月
 *              - this_year: 今年
 *              - last_year: 去年
 *            - type: 统计类型，固定为"revenue"（可选）
 * @param res 响应对象，返回JSON格式：
 *            - data: 数据数组，每个元素包含：
 *              - date: 日期
 *              - revenue: 收入
 *              - orders: 订单数
 *              - average_order_value: 平均订单价值
 *            - message: 状态消息
 *            - success: 操作是否成功
 */
void getRevenueChart(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        std::map<std::string, std::string> bodyJson;
        if (!req.body.empty()) {
            bodyJson = req.queryParams;
        }

        std::string timeRange = bodyJson.count("timeRange") ? bodyJson["timeRange"] : "today";

        std::string today = getToday();
        std::string startDate = today;
        std::string endDate = addDay(today, 1);

        // 处理时间范围
        if (timeRange == "yesterday") {
            startDate = addDay(today, -1);
            endDate = today;
        } else if (timeRange == "this_week") {
            startDate = addDay(today, -7);
        } else if (timeRange == "last_week") {
            startDate = addDay(today, -14);
            endDate = addDay(today, -7);
        } else if (timeRange == "this_month") {
            startDate = addDay(today, -30);
        } else if (timeRange == "last_month") {
            startDate = addDay(today, -60);
            endDate = addDay(today, -30);
        } else if (timeRange == "this_year") {
            startDate = addDay(today, -365);
        } else if (timeRange == "last_year") {
            startDate = addDay(today, -730);
            endDate = addDay(today, -365);
        }

        // 按日期统计收入
        std::string sql = "SELECT DATE(createdAt) AS date, COUNT(*) AS orders, "
                          "SUM(CAST(totalPrice AS DECIMAL(10,2))) AS revenue "
                          "FROM orders WHERE createdAt BETWEEN '" + startDate + "' AND '" + endDate + "' "
                                                                                                      "GROUP BY DATE(createdAt) ORDER BY date;";

        auto result = DBConnector::getInstance()->query(sql);

        std::vector<JsonValue> data;
        for (const auto& row : result) {
            std::map<std::string, JsonValue> datum;
            if (row.count("date")) datum["date"] = JsonValue(row.at("date"));
            if (row.count("revenue")) datum["revenue"] = JsonValue(row.at("revenue"));
            if (row.count("orders")) datum["orders"] = JsonValue(row.at("orders"));

            // 计算平均订单价值
            if (row.count("orders") && row.count("revenue") && !row.at("orders").empty() && !row.at("revenue").empty() && row.at("revenue") != "NULL") {
                int orders = std::stoi(row.at("orders"));
                double revenue = std::stod(row.at("revenue"));
                if (orders > 0) {
                    datum["average_order_value"] = JsonValue(std::to_string(revenue / orders));
                } else {
                    datum["average_order_value"] = JsonValue("0.00");
                }
            } else {
                datum["average_order_value"] = JsonValue("0.00");
            }

            data.push_back(JsonValue(datum));
        }

        std::map<std::string, JsonValue> resMp;
        resMp["data"] = JsonValue(data);
        resMp["message"] = JsonValue("Success");
        resMp["success"] = JsonValue(true);

        res.json(toJson(resMp));
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}
/**
 * @brief 获取分类图表数据
 *
 * @param req 请求对象，JSON body包含：
 *            - timeRange: 时间范围（可选），可选值：
 *              - today: 今天
 *              - yesterday: 昨天
 *              - this_week: 本周
 *              - last_week: 上周
 *              - this_month: 本月
 *              - last_month: 上月
 *              - this_year: 今年
 *              - last_year: 去年
 *            - type: 统计类型，固定为"category"（可选）
 * @param res 响应对象，返回JSON格式：
 *            - data: 数据数组，每个元素包含：
 *              - category: 分类名称
 *              - count: 数量
 *              - percentage: 百分比
 *              - revenue: 收入
 *            - message: 状态消息
 *            - success: 操作是否成功
 */
void getCategoryChart(const Request& req, Response& res) {
    if (! Middleware::requiredMaintenance(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        std::map<std::string, std::string> bodyJson;
        if (!req.body.empty()) {
            bodyJson = req.queryParams;
        }

        std::string timeRange = bodyJson.count("timeRange") ? bodyJson["timeRange"] : "today";

        std::string today = getToday();
        std::string startDate = today;
        std::string endDate = addDay(today, 1);

        // 处理时间范围
        if (timeRange == "yesterday") {
            startDate = addDay(today, -1);
            endDate = today;
        } else if (timeRange == "this_week") {
            startDate = addDay(today, -7);
        } else if (timeRange == "last_week") {
            startDate = addDay(today, -14);
            endDate = addDay(today, -7);
        } else if (timeRange == "this_month") {
            startDate = addDay(today, -30);
        } else if (timeRange == "last_month") {
            startDate = addDay(today, -60);
            endDate = addDay(today, -30);
        } else if (timeRange == "this_year") {
            startDate = addDay(today, -365);
        } else if (timeRange == "last_year") {
            startDate = addDay(today, -730);
            endDate = addDay(today, -365);
        }

        // 按类别统计
        std::string sql = "SELECT t.type AS category, COUNT(*) AS count, "
                          "SUM(CAST(o.totalPrice AS DECIMAL(10,2))) AS revenue "
                          "FROM orders o JOIN tickets t ON o.ticketId = t.id "
                          "WHERE o.createdAt BETWEEN '" + startDate + "' AND '" + endDate + "' "
                                                                                            "GROUP BY t.type;";

        auto result = DBConnector::getInstance()->query(sql);

        // 计算总收入和总数量
        double totalRevenue = 0.0;
        int totalCount = 0;
        for (const auto& row : result) {
            if (row.count("revenue") && !row.at("revenue").empty() && row.at("revenue") != "NULL") {
                totalRevenue += std::stod(row.at("revenue"));
            }
            if (row.count("count") && !row.at("count").empty()) {
                totalCount += std::stoi(row.at("count"));
            }
        }

        std::vector<JsonValue> data;
        for (const auto& row : result) {
            std::map<std::string, JsonValue> datum;
            if (row.count("category")) datum["category"] = JsonValue(row.at("category"));
            if (row.count("count")) datum["count"] = JsonValue(row.at("count"));
            if (row.count("revenue")) datum["revenue"] = JsonValue(row.at("revenue"));

            // 计算百分比
            if (totalRevenue > 0 && row.count("revenue") && !row.at("revenue").empty() && row.at("revenue") != "NULL") {
                double catRev = std::stod(row.at("revenue"));
                double percentage = (catRev / totalRevenue) * 100.0;
                datum["percentage"] = JsonValue(std::to_string(percentage));
            } else {
                datum["percentage"] = JsonValue("0.00");
            }

            data.emplace_back(datum);
        }

        std::map<std::string, JsonValue> resMp;
        resMp["data"] = JsonValue(data);

        res.success(resMp);
    } catch (const std::exception& e) {
        res.error(400, "Invalid request body: " + std::string(e.what()));
    }
}

void getAdminType(const Request& req, Response& res) {

}